package com.scalar.chiptrack.sales.actions.quote;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.packingslip.PackingSlipComparator;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.Quotation;
import com.scalar.chiptrack.sales.SubTotal;
import com.scalar.chiptrack.sales.Customer;
import com.scalar.chiptrack.sales.actions.OrderAction;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.quote.QuotationDAO;
import com.scalar.chiptrack.sales.forms.quote.ApproverQuotationForm;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;

/**
 * Author: Prabhanjan
 * Date: Feb 11, 2004
 * Time: 9:06:07 AM
 */
public class QuotationViewAction extends ChipTrackAction
{
    // ----------------------------------------------------- Instance Variables

    //private static final String ACTION_NAME = "/order.do";  // Added by Basha (08/08/2003)
    private static final String ACTION_NAME = "/quotationView.do"; //modified by varna (09/17/2004)
    public static String coolstatus = null;
    public ApproverQuotationForm subform;

    // --------------------------------------------------------- Public Methods


    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     *
     * @param mapping The ActionMapping used to select this instance
     * @param form The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception Exception if business logic throws an exception
     */
    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response )
            throws Exception
    {

        // Extract attributes and parameters we will need
        subform = ( ApproverQuotationForm ) form;
        String action = request.getParameter ( "action" );

        HttpSession session = request.getSession ();
        User users = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        if ( users == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }
        Quotation quotation = null;
        LineItem lineitem = new LineItem ();

        ActionErrors errors = new ActionErrors ();

        String quotationId = "";
        String quotationNo = "";
        try
        {
            quotationId = request.getParameter ( "quotationId" );
        }
        catch ( NullPointerException e )
        {
            quotationId = "";
        }

        if( quotationId == null || "".equals( quotationId.trim() ) )
        {
        	quotationNo = request.getParameter ( "quotationNo" ); 
        	if( quotationNo != null && !"".equals( quotationNo.trim() )  )
        	{
        		quotationId = QuotationDAO.getQuotationIdByQuotationNo( null, quotationNo ) + "";
        	}
        }
        
        if ( ( quotationId != null ) )
        {
            if ( subform == null )
                subform = new ApproverQuotationForm ();
            if ( users.isActionAllowed ( Functionality.SALES_VIEW_ORDER,
                                         User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }

            if ( quotationId != null )
            {
                quotation = QuotationDAO.loadQuotation ( quotationId, false );
            }
            if ( quotation != null ) {
                Customer customer = new Customer();
                customer.setCustomerId( quotation.getCustomerId() );
                CustomerDAO.getCustomerDetailsForAcknowledgement( null, customer );
                request.setAttribute ( "customer", customer );
            }
            subform.setQuotationId ( quotation.getQuotationId () );
            subform.setQuotationNo ( quotation.getQuotationNo () );
            ArrayList presentList = QuotationDAO.loadOrderLineItemsWithCustomerPartNo ( quotation.getQuotationId (), quotation.getCustomerId () );
            String lastStatus[] = new String[presentList.size ()];

            int totalQty = 0;
            double totalAmt = 0.0;
            double salesTax = 0.0;
            float taxvalue = SalesOrderDAO.getTaxValue ( null, quotation.getSalesTaxType () );
            Float ff = new Float(taxvalue);
            double tax = ff.doubleValue();

            for ( int i = 0; i < presentList.size (); i++ )
            {

                LineItem templineItem = ( LineItem ) presentList.get ( i );
                coolstatus = templineItem.getStatus ();
                lastStatus[i] = coolstatus;
                totalQty = totalQty + templineItem.getQuantity ();
                totalAmt = totalAmt + templineItem.getAmountAsDouble ();
                if ( templineItem.getIsTaxable () )
                {
                    salesTax = salesTax + ( templineItem.getAmountAsDouble () * ( tax / 100 ) );
                }

            }

            quotation.setSalesTaxAsDouble ( salesTax );
            quotation.setSubTotalAsDouble ( totalAmt );
            quotation.setOrderTotalAsDouble ( quotation.getSubTotalAsDouble () + quotation.getFrieghtAsDouble () + quotation.getMiscAsDouble () + quotation.getSalesTaxAsDouble () );

            if( quotation.getShippingAccount() != null && quotation.getShippingAccount().trim().length() > 0 && quotation.getShippingMethodName() != null && quotation.getShippingMethodName().trim().length() > 0 )
            {
                quotation.setShippingAccount( quotation.getShippingMethodName() + "   #   " + quotation.getShippingAccount() );
            }

            subform.setQuotation ( quotation );
            request.setAttribute ( "approverQuotationForm", subform );

            request.setAttribute ( "lineitemstatus", lastStatus );


            if ( presentList.size () == 0 )
                request.setAttribute ( "presentShow", "FALSE" );
            else
                request.setAttribute ( "presentShow", "TRUE" );

            request.setAttribute ( "lineItems", presentList );
            request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( ( ArrayList ) request.getAttribute ( "lineItems" ) ) );
            request.setAttribute ( "termsAndConditions", SalesDAO.loadTermsAndConditionsAsList () );
        }

        if ( "printQuotation".equalsIgnoreCase ( action ) )
        {
            ArrayList linaItemList =  ( ArrayList ) request.getAttribute ( "lineItems" );
            if ( request.getAttribute ( "lineItems" ) != null )
                Collections.sort ( linaItemList, new PackingSlipComparator () );
                request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( linaItemList ) );
                return ( mapping.findForward ( "printQuotation" ) );
        }
        return ( mapping.findForward ( "success" ) );
    }

    public static ArrayList loadLineItemsWithSubTotals ( ArrayList lineItemList )
    {
        ArrayList list = new ArrayList ();
        LinkedHashMap hash = new LinkedHashMap ();
        for ( int i = 0; i < lineItemList.size (); i++ )
        {
            LineItem lineItem = ( LineItem ) lineItemList.get ( i );
            String mfgPartNumber = lineItem.getManufacturingPartNo ();
            if ( !( hash.containsKey ( mfgPartNumber ) ) )
            {
                hash.put ( mfgPartNumber, new ArrayList () );
            }
            ArrayList arrList = ( ArrayList ) hash.get ( mfgPartNumber );
            arrList.add ( lineItem );
        }
        Iterator iterator = hash.keySet ().iterator ();
        LinkedHashMap hashMap = new LinkedHashMap ();

        while ( iterator.hasNext () )
        {
            String str = ( String ) iterator.next ();
            ArrayList arrList = ( ArrayList ) hash.get ( str );
            SubTotal subTotal = new SubTotal();
            double subTotalAmt = 0.0;
            int subTotalQty = 0;
            for ( int i = 0; i < arrList.size (); i++ )
            {
                subTotalAmt = subTotalAmt + ( ( LineItem ) arrList.get ( i ) ).getExtendedPriceForQuote ();
                subTotalQty = subTotalQty + ( ( LineItem ) arrList.get ( i ) ).getQuantity();
            }
            subTotal.setSubTotalQty ( Integer.toString ( subTotalQty ) );
            subTotal.setSubTotalAmt ( StringUtils.formatAmountWithNoOfDecimals ( subTotalAmt ) );
            hashMap.put ( arrList, subTotal );

        }
        list.add ( hashMap );

        return list;
    }


    public static ArrayList loadLineItemsWithSubTotalsForAirgo ( ArrayList lineItemList )
        {
            ArrayList list = new ArrayList ();
            LinkedHashMap hash = new LinkedHashMap ();
            for ( int i = 0; i < lineItemList.size (); i++ )
            {
                LineItem lineItem = ( LineItem ) lineItemList.get ( i );
                String mfgPartNumber = lineItem.getManufacturingPartNo ();
                if ( !( hash.containsKey ( mfgPartNumber ) ) )
                {
                    hash.put ( mfgPartNumber, new ArrayList () );
                }
                ArrayList arrList = ( ArrayList ) hash.get ( mfgPartNumber );
                arrList.add ( lineItem );
            }
            Iterator iterator = hash.keySet ().iterator ();
            LinkedHashMap hashMap = new LinkedHashMap ();

            while ( iterator.hasNext () )
            {
                String str = ( String ) iterator.next ();
                ArrayList arrList = ( ArrayList ) hash.get ( str );
                SubTotal subTotal = new SubTotal();
                double subTotalAmt = 0.0;
                int subTotalQty = 0;
                int subTotalProposedQty = 0;
                for ( int i = 0; i < arrList.size (); i++ )
                {
                    subTotalAmt = subTotalAmt + ( ( LineItem ) arrList.get ( i ) ).getExtendedPriceForQuote ();
                    subTotalQty = subTotalQty + ( ( LineItem ) arrList.get ( i ) ).getQuantity();
                    subTotalProposedQty = subTotalProposedQty + ( ( LineItem ) arrList.get ( i ) ).getQuotedQuantity();
                }
                subTotal.setSubTotalQty ( Integer.toString ( subTotalQty ) );
                subTotal.setSubTotalAmt ( StringUtils.formatAmountWithNoOfDecimals ( subTotalAmt ) );
                subTotal.setSubTotalProposedQty( Integer.toString (subTotalProposedQty) );
                hashMap.put ( arrList, subTotal );

            }
            list.add ( hashMap );

            return list;
        }
}